<template>
  <el-card style="width: 500px;">
    <el-form :model="user" :rules="rules" ref="userForm">
      <el-form-item prop="oldPassword">
        <el-input placeholder="请旧密码" size="medium" style="margin: 5px 0" prefix-icon="el-icon-lock" show-password
                  v-model="user.oldPassword"></el-input>
      </el-form-item>
      <el-form-item prop="NewPassword">
        <el-input placeholder="请输入新的密码" size="medium" style="margin: 5px 0" prefix-icon="el-icon-lock" show-password
                  v-model="user.newPassword"></el-input>
      </el-form-item>
      <el-form-item prop="ConfirmPassword">
        <el-input placeholder="确认密码" size="medium" style="margin: 5px 0" prefix-icon="el-icon-lock" show-password
                  v-model="user.confirmPassword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update">确 定</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "Password",
  data(){
    return{
      user:{
        username:localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")).username : '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ],
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请确认密码', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  methods:{
    update(){
      this.$refs['userForm'].validate((valid) => {
        if (valid){
          if (this.user.newPassword !== this.user.confirmPassword) {
            this.$message.error("两次输入的密码不正确")
            return false
          }
          this.request.post("/sys/password",this.user).then(res=>{
            console.log(this.user)
            if (res.code===200){
              this.request.post("/sys/update",this.user).then(res=>{
                if (res.code===200){
                  this.$message.success("更新成功")
                  this.$store.commit("logout")
                }else {
                  this.$message.error(res.message)
                }
              })
            }
          })
        }
      })

    }
  }
}
</script>

<style scoped>

</style>